//
//  AmbitusTableViewController.m
//  TravelToHelp
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 冯贵宾. All rights reserved.
//

#import "AmbitusTableViewController.h"
#import "AmbitusListViewController.h"

@interface AmbitusTableViewController ()

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) AppDelegate *app;

@property (nonatomic, strong) DDIndicator *indicator;

@property (nonatomic, strong) UIView *viewV;

@end

@implementation AmbitusTableViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadData" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
     _app = [[AppDelegate alloc] init];
    self.view.backgroundColor = [UIColor whiteColor];
    [self freshHeader];
   // [self setUpData];
    [self setNavigationBar];
    [self addInternetObserver];
}

// 通知网络状态
- (void)addInternetObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataWithInternet:) name:@"reloadData" object:nil];
}

- (void)reloadDataWithInternet:(NSNotification *)notification
{
    [self setUpData];
}


- (void)setNavigationBar
{
    self.navigationItem.title = @"城市列表";
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backNew.png"] style:(UIBarButtonItemStylePlain) target:self action:@selector(actionLeftButton:)];
  
    self.navigationItem.leftBarButtonItem = leftButton;
}

- (void)actionLeftButton:(UIBarButtonItem *)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)freshHeader
{
    if ([_app internetReachableOrNot]) {
        self.tableView.header = [LYBAnimationHeader headerWithRefreshingTarget:self refreshingAction:@selector(setUpData)];
        [self.tableView.header beginRefreshing];
    } else {
        [self alertController];
    }
}

- (void)setUpData
{
     if ([_app internetReachableOrNot]) {
         
    NSString *urlString = [NSString stringWithFormat:@"%@",@"http://api.lanrenzhoumo.com/district/list/allcity?session_id=00004016b3e14bbea40c1aa1a14c2273a35352"];
    NSString *url = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
    [request setHTTPMethod:@"GET"];
    self.dataArray = [NSMutableArray array];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
            return ;
        } else {
            NSDictionary *tempDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSMutableArray *tempArr = [tempDict valueForKey:@"result"];
            for (NSDictionary *dic in tempArr) {

               AmbitusCityTypeModel *model = [[AmbitusCityTypeModel alloc] init];
                [model setValue:[dic valueForKey:@"begin_key"] forKey:@"begin_key"];
                NSMutableArray *tem = [NSMutableArray array] ;
                for (NSDictionary *dict in [dic valueForKey:@"city_list"]) {
                
                    AmbitusCityModel *model1 = [[AmbitusCityModel alloc] init];
                    [model1 setValuesForKeysWithDictionary:dict];
                    [tem addObject:model1];
                    
                }
               
                [model setValue:tem forKey:@"city_list"];
                [self.dataArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView.header endRefreshing];
                [self.tableView reloadData];
                [self stopLoading];
            });
        }
    }];
    [dataTask resume];
     } else {
        [self alertController];
     }

}
- (void)alertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的当前网络中断或网络信号差, 请检查网络后重新进入!!" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
    
    // 加载动画
- (void)addAnimation
{
    _viewV = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth / 2 - 100, kScreenHeight / 2 - 80, 200, 80)];
    _viewV.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0];
    _viewV.layer.cornerRadius = 10;
    _viewV.layer.masksToBounds = YES;
    [self.view addSubview:_viewV];
    self.indicator = [[DDIndicator alloc] initWithFrame:CGRectMake(_viewV.width / 2 - 20, _viewV.height / 2 - 20 , 40, 40)];
        
    [_viewV addSubview:self.indicator];
     [self.indicator startAnimating];
    // [self performSelector:@selector(stopLoading:) withObject:self.indicator afterDelay:5];
        
}
    
- (void)stopLoading
{
    [_indicator stopAnimating];
    [self.viewV removeFromSuperview];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TableView的代理方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    AmbitusCityTypeModel *model = self.dataArray[section];
    return model.city_list.count;
}



- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
     AmbitusCityTypeModel *model = self.dataArray[section];
    if (section == 0) {
        model.begin_key = @"热门城市";
    }
    return model.begin_key;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *array = [NSMutableArray array];
    if (self.dataArray.count > 0) {
     for (int i = 0; i < self.dataArray.count; i++) {
        if (i == 0) {
            continue;
        }
        AmbitusCityTypeModel *model = self.dataArray[i];
        [array addObject:model.begin_key];
    }
  }
    return array;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"AmbitusCityList";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    if (self.dataArray.count > 0) {
        AmbitusCityTypeModel *model = self.dataArray[indexPath.section];
        AmbitusCityModel *cityModel = model.city_list[indexPath.row];
        cell.textLabel.text = cityModel.city_name;
    }
     return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    AmbitusCityTypeModel *model = self.dataArray[indexPath.section];
     AmbitusCityModel *cityModel = model.city_list[indexPath.row];
    [_delegate reloadAmbitusListById:cityModel.city_id cityName:cityModel.city_name];
    [self.navigationController popViewControllerAnimated:YES];
}



@end
